package com.grape.service.take_delivery.impl;

import java.util.Date;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.grape.dao.take_delivery.OrderRepository;
import com.grape.domain.base.Area;
import com.grape.domain.base.Courier;
import com.grape.domain.base.FixedArea;
import com.grape.domain.base.SubArea;
import com.grape.domain.take_delivery.Order;
import com.grape.domain.take_delivery.WorkBill;
import com.grape.service.base.AreaService;
import com.grape.service.base.FixedAreaService;
import com.grape.service.take_delivery.OrderService;
import com.grape.service.take_delivery.WorkBillService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {

	@Autowired
	AreaService as;
	@Autowired
	FixedAreaService fs;
	@Autowired
	OrderRepository or;
	@Autowired 
	WorkBillService wbs;

	// ActiveMQ
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jt;

	@Override
	public void save(Order model) {
		
		Area sendArea = model.getSendArea();
		Area recArea = model.getRecArea();

		Area sendA = as.findByProvinceAndCityAndDistrict(sendArea.getProvince(), sendArea.getCity(),
				sendArea.getDistrict());
		Area recA = as.findByProvinceAndCityAndDistrict(recArea.getProvince(), recArea.getCity(),
				recArea.getDistrict());

		if (sendA == null || recA == null) {
			System.out.println("未录入的区域无法继续进行取件操作");
			return;
		}

		model.setSendArea(sendA);
		model.setRecArea(recA);

		// 根据定区查找快递员
		String dqid = WebClient.create("http://localhost:10001/crm_management/services/customerService/findDqidByAddress")
				.replaceQueryParam("address", model.getSendAddress())
				.accept(MediaType.APPLICATION_XML).get(String.class);

		System.out.println("定区id: "+dqid);
		
		if (!dqid.equals("null")) {
			FixedArea fa = fs.findOne(dqid);
			if (fa.getCouriers().iterator().hasNext()) {
				completeOrder(fa.getCouriers().iterator().next(), model);
				or.save(model);
				return;
			}
		}

		if (dqid.equals("null")) {
			for (SubArea subA : sendA.getSubareas()) {
				if (model.getSendAddress().contains(subA.getKeyWords())
						|| model.getSendAddress().contains(subA.getAssistKeyWords())) {
					if (subA.getFixedArea().getCouriers().iterator().hasNext()) {
						completeOrder(subA.getFixedArea().getCouriers().iterator().next(), model);
						or.save(model);
						return;
					}
				}
			}
		}

		// System.out.println("分单失败进入人工分单");
		model.setOrderType("2");
		or.save(model);

	}

	// 根据定区找到负责的快递员,发短信,生成工单
	public void completeOrder(final Courier next, final Order model) {
		// System.out.println("自动分单成功");	
		model.setOrderType("1");
		model.setCourier(next);

		WorkBill wb = new WorkBill();
		wb.setType("新");
		wb.setPickstate("新单");
		wb.setBuildtime(new Date());
		wb.setRemark(model.getRemark());
		// 揽件验证码
		String r4 = RandomStringUtils.randomNumeric(4);
		wb.setSmsNumber(r4);
		wb.setOrder(model);
		wb.setCourier(next);
		wbs.save(wb);
		System.out.println("工单创建保存完成");
		
		
		/*// 短信模板,需开启bos_sms
		final String str = next.getName() + "请前往" + model.getSendAddress() + "取件,取件验证码为" + r4 + "客户电话: "
				+ model.getSendMobile() + "客户留言: " + model.getRemark();

		// 交给ActiveMQ
		jt.send("bos_sms", new MessageCreator() {

			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone", next.getTelephone());
				mapMessage.setString("msg", str);
				return mapMessage;
			}
		});*/

	}

	@Override
	public Order findByOrderNum(String orderNum) {
		return or.findByOrderNum(orderNum);
	}

}
